// var orderbill = require('../../js/shop/order.js').order
const chooseLocation = requirePlugin('chooseLocation');
var actmember = require('../../../xc/model/member');
var paytool = require('./js/paytool');

// var util = require('../../../utils/util.js');
var actcart = require('../../../xc/sys/cart')
var acttoolv2 = require('../../../xc/sys/toolv2')
var order_bill = require('../model/integralorder_bill.js')
var actcouponbill = require('../../../xc/model/coupon_cont')
import Notify from '../../../vant/weapp/notify/notify';
var app = getApp();
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    calcsamecityinfo: null,
    delivery_config: null,
    expressaddr: null,
    //订单默认参数
    paytype: -1, //支付类型1.微信支付
    // 导航
    nav: [],
    navCur: -1,
    deliverymode: 1, //navCur =0 的有效  1自提  2团长配送    
    activitymodel: {
      clienttimestampdeviation: 0, //服务器跟客户端 的时间误差
      haslimite: false,
      intervalid: -1 //自己执行判断   
    },
    priceinfo: {},
    freight: 0, //快递费   actcoupon  freight paytype expressaddr paytype deliverymode
    actcoupon: null,
    actclub: null,
    remark: "",
    iscart: "-1", 
    memberinfo: null,
    paymentmethod: [],
    clubdelivery:1, //自提
    // balanceloadsuccess: false,
    pageshow: true,
  },
  selectchange(e) {     
    console.log("e.detaile.detail=----e.detaile.detail")
    console.log(e.detail)
    var status = e.detail;
    this.setData({
      pageshow: status
    })
  },
  /**
 * 选择优惠券
 */
  paytypeChange(e) {
    this.setData({ paytype: e.detail })
  },
  updatesimplevipinfo() {
    var that = this;
    actmember.simplevipinfo().then(function (res) {
      if (res["status"] == 1 && res["obj"]) {
        var updatemodel = {}
        updatemodel["memberinfo.amount"] = res["obj"]["amount"]
        updatemodel["memberinfo.vips"] = res["obj"]["vips"]
      }
      that.setData(updatemodel)
    })
  },
  afterlogin(options, configdata, userinfo) {  
    this.setData({memberinfo:userinfo.memberinfo})
    //最新vip会员最新余额
    this.updatesimplevipinfo();
  },
  usecoupon() {
    var that = this;
    this.authop("coupon").then(rest => {
      if (rest["status"] != 1) {
        wx.showToast({
          title: rest["message"] ? rest["message"] : "获取信息失败",
        })
      }
      else {
        var userinfo = rest["userinfo"]
        var Comcouponpro = that.selectComponent("#couponpro")
        Comcouponpro.showinfo()
      }
    })
  },

  click_nav(e) {
    var that = this;
    this.setData({
      navCur: e.currentTarget.dataset.id,
      freight: 0
    })
    this.changnav()
  },
  changnav() {
    // var navCur = this.data.navCur
    // if (navCur == 0 || navCur == 3) {
    //   var address = this.selectComponent("#address");    
    //   address.set_init(navCur);
    // } else if (navCur == 1 || navCur == 2) {
    //   var address = this.selectComponent("#clubaddress");
    //   address.set_init(navCur);
    // }
    console.log("this.data.type")
    console.log(this.data.type)
    if(this.data.type && this.data.type!=2){
      var address = this.selectComponent("#address");    
      address.set_init(0);
    }
    this.billpriceinfo();
  },

  //选择优惠券回调
  couponblack(e) {
    var coupon = e.detail
    if (coupon) {
      var discountmoney = actcouponbill.discountmoney(coupon, this.data.cartdadta)
      coupon["discountmoney"] = discountmoney
    }
    this.setData({ actcoupon: coupon })
    this.billpriceinfo()
  },
  //加载完成加载
  xcloaddata: function (options, config) {   
    // console.log("config")
    // console.log(config)
    var  {nav,navCur,delivery_config,paymentmethod,paytype}= paytool.getnav(config)
    this.data.iscart = options.iscart
    var that = this;
    var cartdadta = app.globalData.temcart["data"]
    // console.log("cartdadta")
    // console.log(cartdadta)
    var type=cartdadta[0]['type'];
    // console.log("type")
    // console.log(type)
    
    this.setData({ nav, navCur, delivery_config,paymentmethod,paytype,cartdadta,type })  
    // var Comcouponpro = that.selectComponent("#couponpro")
    // Comcouponpro.initcoupon(cartdadta)
    that.changnav()
    // that.getmycloubinfo()
  },
  getmycloubinfo() {
    var app = getApp()
    if (!app.globalData.clubinfo) {
      actmember.getmycloubinfo().then(res => {
        if (res["status"] == 1) {
          var clubinfo = res["obj"]
          if (app.globalData.lng) {
            var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
            clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
          }
          app.globalData.clubinfo = clubinfo;
        }
      })
    }
    // app.globalData.clubinfo 

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //针对门店配送计算
  shopdeliverychage(ev){
 
    var detail= ev.detail
   
    if(detail.clubdelivery==1){
      this.setData({
        clubdelivery:1,
        freight: 0
      })
      this.data.expressaddr=null
      this.billpriceinfo();
    }else if (detail.clubdelivery==2){
      this.setData({
        clubdelivery:2,       
      })
      if(detail.obj)
      {
        this.calcsamecity(null,detail.obj["distance"])
        this.data.expressaddr=detail.obj
      }
   
    }  

  },
  //同城快递计算
  calcsamecity(intracity,distance) {
    
    if(!intracity)
    {
      intracity = this.data.delivery_config.intracity;
    }   
    if (!intracity) {
      return;
    }   
    if(!distance)
    {
      var expressaddr = this.data.expressaddr
      distance= expressaddr.distance;
    } 
    console.log("888888888888")
  var {calcsamecityinfo,freight}= paytool.calcsamecity(intracity,distance)
  console.log(calcsamecityinfo)

  if(calcsamecityinfo["status"]==1){
    this.setData({calcsamecityinfo,freight})
    this.billpriceinfo();
  }
  else{
    this.data.calcsamecityinfo =calcsamecityinfo; 
  }
   

  },
  //获取运费
  getexpress: function (pro, addr) {
 
    var that = this;
    if (!pro) {
      pro = this.data.cartdadta
    }
    if (!addr) {
      addr = this.data.expressaddr
    }
    if (pro && addr) {
      if (that.data.navCur == 3) {
        this.calcsamecity();
        return;
      }
      order_bill.getexpress(pro, addr).then(function (paradata) {
        if (paradata.failnum > 0) {
        }
        else {
          that.setData({
            freight: paradata.totalmoney
          })
        }
        that.billpriceinfo();
      })
    }
  },
  //改地址切换运费
  selectaddrfunc: function (e) {
    this.data.expressaddr = e.detail;
    if (e.detail != null) {
      this.getexpress(this.data.cartdadta, e.detail)
    }

  },
  //改团点地址切换运费 
  selectgroupaddr: function (e) {
    this.data.actclub = e.detail
    var that = this;
    this.setData({ freight: 0 })
     
    that.billpriceinfo();
  },
  //计算产品价格
  billpriceinfo: function () {   
    
    var {prototalprice,totalprice,pronums,paymoney,integral} =paytool.billpriceinfo(this.data.cartdadta,this.data.freight,this.data.actcoupon)


    console.log("fdfsdf")
    console.log( {prototalprice,totalprice,pronums,paymoney })
    // if(paymoney==0){
    //   this.setData({paytype:0})
    // }
    this.setData({priceinfo: {prototalprice,totalprice,pronums,paymoney,integral } })      
   

    this.selectComponent('#van-submit-bar').updatePrice()
    if (this.data.activitymodel.haslimite) {
      this.autoexcel();
    }

  },
  autoexcel: function () {
    var that = this;
    if (that.data.activitymodel.intervalid != -1) {
      clearInterval(that.data.activitymodel.intervalid)
    }
    that.data.activitymodel.intervalid = setInterval(function () {
      that.setData({
        "list": that.data.list
      });
    }, 1000)
  },
 
  //创建订单  
  createbill: function (e) {
    var app = getApp()
    var that = this;
    var ordermodel = {};
    //订单内容
    var htpro = {};
    var proinfor = that.data.cartdadta[0];
    console.log(proinfor);
    // return;

    that.data.cartdadta.forEach(function (item) {
      htpro[item["keyval"]] = {
        num: item["num"]
      };
    })
    
    ordermodel["htpro"] = htpro;
    if(that.data.cartdadta['0']['rewordid']){
      ordermodel['rewordid']=that.data.cartdadta['0']['rewordid']
    }

    var navCur = this.data.navCur
    if (this.data.type==1) {
      ordermodel["addrinfo"] = this.data.expressaddr // mark: xxx
      ordermodel["distributionmode"] = 1
    }else if (this.data.type==2){
      ordermodel["distributionmode"] = 0
    }

    if (this.data.actcoupon) {
      ordermodel["coupon_id"] = this.data.actcoupon["bindid"]
    }
    var publicdata = ['paytype', 'freight', 'remark'];
    for (var i in publicdata) {
      ordermodel[publicdata[i]] = this.data[publicdata[i]]
    }

    if (this.data.type==1) {
      if (!this.data.expressaddr.id) {
        var address = this.selectComponent("#address");
        address.noheadformadd(function (relsut) {
          if (relsut["status"] == 1) {
            that.data.expressaddr.id = relsut["obj"].id;
            that.postorder(ordermodel)
          }
        })
        return;
      }
    }
    this.postorder(ordermodel)
  },
//提交订单
  postorder(ordermodel) {
    var that = this;
    order_bill.createorder(ordermodel).then(function (restmodel) {
      if (that.data.iscart) {
        actcart.removeselected();
      }
      if (restmodel["status"] == 1) {
        // console.log()
        var template_ids = restmodel["template_ids"]
        if (restmodel["paytype"] == 1 || restmodel["paytype"] == 3) {
          var pay_params = restmodel["pay_params"];
          wx.requestPayment({
            timeStamp: pay_params["timeStamp"],
            nonceStr: pay_params["nonceStr"],
            package: pay_params["package"],
            signType: pay_params['signType'],
            paySign: pay_params["paySign"],
            success(res) {
              if (template_ids && template_ids.length > 0) {
                wx.requestSubscribeMessage({
                  tmplIds: template_ids,
                  success(res) { }
                })
              }
              order_bill.queryorder(restmodel["id"]).then(function (queryreslut) {
                if (queryreslut["status"] == 1) {
                  wx.redirectTo({
                    url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
                  })
                }
              })
            },
            fail(res) {
              if (res["errMsg"] == "requestPayment:fail cancel") {
                wx.showModal({
                  title: '订单未支付',
                  content: '订单未支付',
                  showCancel: false,
                  success(res) {
                    wx.redirectTo({
                      url: "../order/index?opstatus=1",
                    })
                  }
                })
              }

            }
          })
        } else if (restmodel["paytype"] == 2 || restmodel["paytype"] ==0) {
          //余额支付
          if (template_ids && template_ids.length > 0) {
            wx.requestSubscribeMessage({
              tmplIds: template_ids,
              success(res) {
                order_bill.sendnotice_buy(restmodel["ordernum"]).then(function (restmodel) {
                  console.log(restmodel)
                })
              }
            })
          }
          if(restmodel['member']){
            app.globalData.member=restmodel['member']
          }
          wx.redirectTo({
            url: '/xc_lshop/integralmall/my/exchange',
          })
         
        }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  
    //系统组件选择地址回调
    const location = chooseLocation.getLocation();
    if (location) {
      var address =null
      if(this.data.navCur==0 || this.data.navCur==3){
          address = this.selectComponent("#address");
      }
      else if  (this.data.navCur==1 || this.data.navCur==2){
        address = this.selectComponent("#clubaddress");
      }
      address.chooseLocation(location)
     
    }
  },
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})